package com.tao.order.service.impl;

import com.tao.order.bean.Order;
import com.tao.order.feign.ProductFeignClient;
import com.tao.order.service.OrderService;
import com.tao.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author xujingtao
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public Order createOrder(Long productId, Long userId) {
        Product product = productFeignClient.getProductById(productId);
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Order order = new Order();
        order.setId(1L);
        // TODO 获取总价
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("NickName");
        order.setAddress("地址");
        // TODO 获取商品列表
        order.setProductList(List.of(product));
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = String.format("http://%s:%s/product/%s", serviceInstance.getHost(), serviceInstance.getPort(), productId);
        return restTemplate.getForObject(url, Product.class);
    }

    // 负载均衡
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        ServiceInstance chooseInstance = loadBalancerClient.choose("service-product");
        log.info("serviceInstance: {}", chooseInstance.getHost()+chooseInstance.getPort());
        String url = String.format("http://%s:%s/product/%s", chooseInstance.getHost(), chooseInstance.getPort(), productId);
        return restTemplate.getForObject(url, Product.class);
    }

    // 负载均衡注解
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        String url = String.format("http://service-product/product/%s", productId);
        return restTemplate.getForObject(url, Product.class);
    }

}
